package com.booksystem.campuslibrarymanagementsystem.controller.user;


import com.booksystem.campuslibrarymanagementsystem.commen.request.userquest.BookAppointment.*;
import com.booksystem.campuslibrarymanagementsystem.commen.request.userquest.ReservaTable;
import com.booksystem.campuslibrarymanagementsystem.commen.result.Result;
import com.booksystem.campuslibrarymanagementsystem.commen.result.userresuilt.ReservationTablelist;
import com.booksystem.campuslibrarymanagementsystem.entity.BooksTable;
import com.booksystem.campuslibrarymanagementsystem.entity.ReservationTable;
import com.booksystem.campuslibrarymanagementsystem.service.ReservationTableService;
import com.booksystem.campuslibrarymanagementsystem.utils.JwtUtil;
import com.booksystem.campuslibrarymanagementsystem.utils.TimeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RequestMapping("/User")
@Api(tags ="图书预约")
@RestController
public class BookAppointmentCointroller {


    @Autowired
    ReservationTableService reservationTableService;
    public BookAppointmentCointroller(ReservationTableService reservationTableService) {
        this.reservationTableService = reservationTableService;
    }

    /*
      图书预约
      1.账户id(学号)
      2，图书id  不能重复预约
      3，预约时间（自动生成）
      4,审批状态默认为未通过
     */
    @PostMapping("/bookappointment")
    @ApiOperation(value = "图书预约", notes = "预约图书")

    public Result BookAppointment (@RequestBody BookAppoint bookAppoint){
        Map<String, Object> parsed =JwtUtil.tokenPre(bookAppoint.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            Object account = parsed.get("account");
            if (identity.equals("user")) {
                int bookid =bookAppoint.getBookid();//图书id

                if (bookid <= 0) {
                    // 如果bookid不是一个正数，则认为它是无效的
                    System.out.println("Invalid book ID: " + bookid);
                    return Result.fail("无效的图书ID");
                }
                String time = TimeUtil.getTime();//自动生成预约时间

                //检查图书id是否存在
                BooksTable aa = reservationTableService.aaa(bookid);
                if(aa==null){
                    return Result.fail(String.format("该图书不存在，无法预约图书：%s", bookid));
                }
                // 检查该用户是否已经预约了这本书，并且预约状态为“已通过”
                List<ReservationTable>  existingBorrow = reservationTableService.existsByAccountAndBookidi((String) account, bookid);
                if (existingBorrow != null && !existingBorrow.isEmpty()) {
                    for (ReservationTable entry : existingBorrow) {
                        if ("已通过".equals(entry.getStatus())) {//已通过
                            break; // 退出循环
                        } else {
                            // 如果已通过，不允许再次预约
                            return Result.fail(String.format("您已经预约过这本书：%s", bookid));
                        }
                    }
                }

                // 查找图书，确认图书借出数和总数
                ReservaTable book = reservationTableService.queryid(bookid);
                if (book == null || !book.canBeBorrowed()) {
                    ReservationTable bb = new ReservationTable();
                    bb.setAccount((String) account);
                    bb.setBookid(bookid);
                    bb.setReservationdate(time);
                    bb.setStatus("未审批");

                    int a = reservationTableService.add(bb);
                    if (a>0) {
                        return Result.success(bb,1);
                    } else {
                        return Result.fail((String.format("该账户预约失败：%s,请重新预约",(String) account)));
                    }

                }else {
                    return Result.fail("图书可借阅数量足够,请借阅,不能够预约！");
                }

            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
    }


    /*
    取消自己预约的图书
    1，通过账户id,图书id,找到该预约信息
    2，输入状态将不通过改为用户取消（只能进行用户取消）
    3，预约取消成功
     */
    @PostMapping("/updatestatus")
    @ApiOperation(value = "取消预约信息", notes = "预约之后进行取消预约图书")
    public Result updatestatus (@RequestBody CancelBookAppoint cancelBookAppoint){
        Map<String, Object> parsed = JwtUtil.tokenPre(cancelBookAppoint.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            Object account = parsed.get("account");
            if (identity.equals("user")) {
                int bookd =cancelBookAppoint.getReservationid();//预约id
                String statu = "用户取消";//状态
                if ("用户取消".equals(statu)) {
                    int aa = reservationTableService.updatestatus((String) account,bookd,statu);
                    if (aa>0) {
                        return Result.success(aa,1);
                    } else {
                        return Result.fail("预约取消失败！");
                    }
                }
                return Result.fail("只能进行取消预约图书操作");

            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
    }
    /*
    图书预约列表
    通过预约用户id查看所有预约列表
     */
    @PostMapping("/bookappoint")
    @ApiOperation(value = "图书预约列表", notes = "查看所有预约列表")

    public Result<List<ReservationTablelist>> selectBookAppointment (@RequestBody BookAppointlist bookAppointlist){
        Map<String, Object> parsed = JwtUtil.tokenPre(bookAppointlist.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            Object account = parsed.get("account");
            if (identity.equals("user")) {

                //根据预约账户id查询所有预约列表
                List<ReservationTablelist>  hhh = reservationTableService.appointlist((String) account);
                if (hhh.isEmpty()) {
                    return Result.fail("该预约账户id没有预约图书，请进行预约？");
                } else {
                    return Result.success(hhh,1);
                }
            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }

    }

    /*
    通过判断状态（未通过，通过，用户取消）
    可以查看所有未通过的列表和所有通过，用户取消的列表
     */
    @PostMapping("/bookappointstatus")
    @ApiOperation(value = "查看是否通过图书预约列表", notes = "可以查看所有未通过的列表和所有通过,用户取消的列表")
    public Result selectBookstatusAppointment (@RequestBody BookAppointStatus bookAppointStatus) {
        Map<String, Object> parsed = JwtUtil.tokenPre(bookAppointStatus.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            Object account = parsed.get("account");
            if (identity.equals("user")) {
                String statu = bookAppointStatus.getStatus();
                // 判断状态是否为空
                if (statu == null || statu.trim().isEmpty()) {
                    //根据预约账户id查询所有预约列表
                    List<ReservationTablelist>  hhh = reservationTableService.appointlist((String) account);
                    if (hhh.isEmpty()) {
                        return Result.fail("该预约账户id没有预约图书，请进行预约？");
                    } else {
                        return Result.success(hhh,1);
                    }

                }

                List<ReservationTablelist> statusList = null;
                if ("已通过".equals(statu)) {
                    statusList = reservationTableService.appointliststatus((String) account,statu);
                } else if ("未通过".equals(statu)) {
                    statusList = reservationTableService.appointliststatus((String) account,statu);
                } else if ("未审批".equals(statu)) {
                    statusList = reservationTableService.appointliststatus((String) account,statu);
                } else if("用户取消".equals(statu)){
                    statusList = reservationTableService.appointliststatus((String) account,statu);
                }else {
                    return Result.fail("无效的状态值");
                }
                // 检查列表是否为空
                if (statusList.isEmpty()) {
                    return Result.fail("没有找到账户id为 '" +(String) account + "状态为 '"+ statu + "' 的预约记录");
                } else {
                    return Result.success(statusList, statusList.size());
                }
            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
    }


    @PostMapping("/deleteappoint")
    @ApiOperation(value = "删除预约记录",notes = "账户id，预约id进行删除该账户下该图书的预约记录")
    public Result deleteCollection(@RequestBody DeletBorrowAppoint deletBorrowAppoint) {
        Map<String, Object> parsed = JwtUtil.tokenPre(deletBorrowAppoint.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            Object account = parsed.get("account");
            if (identity.equals("user")) {
                int  bookid =deletBorrowAppoint.getReservationid();  //预约id
                int hh = reservationTableService.deleteByAccountAndBookid((String) account, bookid);
                // 首先检查该用户是否已经收藏了这本书
                if (hh>0) {
                    return  Result.success("成功删除该图书预约记录",1);
                }
                return Result.fail(String.format("没有该图书的预约记录：%s", bookid));
            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
    }

}
